package com.hoshiicloud.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hoshiicloud.common.rpc.Response;
import com.hoshiicloud.rbac.entity.SysRoles;
import com.hoshiicloud.stock.entity.Warehouse;
import com.hoshiicloud.user.entity.company.Company;
import com.hoshiicloud.user.entity.store.PlatStore;
import com.hoshiicloud.user.entity.store.StoreDepartment;
import com.hoshiicloud.user.entity.store.StoreUsers;
import com.hoshiicloud.user.entity.usercenter.PlatConsumer;
import com.hoshiicloud.user.mapper.store.StoreUsersMapper;
import com.hoshiicloud.user.param.PolymerizeStore;
import com.hoshiicloud.user.param.rbac.SysUsersQueryParam;
import com.hoshiicloud.user.param.store.StoreDepartmentQueryParam;
import com.hoshiicloud.user.param.store.StoreUsersQueryParam;
import com.hoshiicloud.user.service.IStoreManageService;
import com.hoshiicloud.user.service.IWarehouseService;
import com.hoshiicloud.user.service.company.ICompanyService;
import com.hoshiicloud.user.service.rbac.ISysRolesService;
import com.hoshiicloud.user.service.store.PlatStoreService;
import com.hoshiicloud.user.service.store.StoreDepartmentService;
import com.hoshiicloud.user.service.store.StoreUsersService;
import com.hoshiicloud.user.service.usercenter.IPlatConsumerService;
import com.hoshiicloud.user.vo.store.StoreUsersVO;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author chenjie
 * @date 2019/8/9-13:51
 * @email rogercj1@126.com
 */
@Service
public class StoreManageServiceImpl extends ServiceImpl<StoreUsersMapper, StoreUsers> implements IStoreManageService {

    @Autowired
    private PlatStoreService platStoreService;

    @Autowired
    private StoreDepartmentService storeDepartmentService;

    @Autowired
    private StoreUsersService storeUsersService;

    @Autowired
    private IWarehouseService iWarehouseService;

    @Autowired
    private IPlatConsumerService iPlatConsumerService;

    @Autowired
    private ISysRolesService sysRolesService;

    @Autowired
    private ICompanyService companyService;


    /**
     * 创建店铺聚合服务
     * @param polymerizeStore
     * @return
     */

    @Override
    public boolean createStore(PolymerizeStore polymerizeStore){
        //创建店铺
        PlatStore platStore = new PlatStore();
        BeanUtils.copyProperties(polymerizeStore, platStore);
        platStore.setCharge(polymerizeStore.getStoreCharge());
        long addStoreId = 0;
        addStoreId = platStoreService.insert(platStore);
        //**********************************
        //创建店铺部门
        StoreDepartment storeDepartment = new StoreDepartment();
        BeanUtils.copyProperties(polymerizeStore, storeDepartment);
        storeDepartment.setCharge(polymerizeStore.getDeptCharge());
        storeDepartment.setStoreId(addStoreId);
        long addDepartmentId = 0;
        addDepartmentId = storeDepartmentService.insert(storeDepartment);
        //**********************************
        //创建店铺员工
        StoreUsers storeUsers = new StoreUsers();
        BeanUtils.copyProperties(polymerizeStore, storeUsers);
        storeUsers.setStoreId(platStore.getId());
        storeUsersService.save(storeUsers);
        //**********************************
        //创建店铺消费者
        PlatConsumer platConsumer = new PlatConsumer();
        BeanUtils.copyProperties(polymerizeStore, platConsumer);
        platConsumer.setRegisteredStoreId(addStoreId);
        iPlatConsumerService.insert(platConsumer);
        //**********************************
        //创建店铺仓库
        Warehouse warehouse = new Warehouse();
        BeanUtils.copyProperties(polymerizeStore, warehouse);
        warehouse.setCharge(polymerizeStore.getWarehouseCharge());
        warehouse.setWhname(polymerizeStore.getStoreName());
        warehouse.setWhcode("W"+String.valueOf((int)((Math.random()*9+1)*100000)));
        iWarehouseService.insert(warehouse);
        //**********************************
        return true;
    }

    /**
     * 店铺管理-->员工列表
     * @param page
     * @param param
     * @param storeId
     * @param comanyId
     * @return
     */
    @Override
    public Response storeUserPageList(IPage<StoreUsersVO> page, @Param("param")StoreUsersQueryParam param, Long storeId,Long comanyId){
        Map addMap = new HashMap<>();
/*        StoreUsersQueryParam storeUsersQueryParam = new StoreUsersQueryParam();
        storeUsersQueryParam.setPageNumber(String.valueOf(page.getCurrent()));
        storeUsersQueryParam.setPageSize(String.valueOf(page.getSize()));*/
        IPage<StoreUsersVO> newPage = storeUsersService.storeUserPageList(page,param);
        StoreDepartmentQueryParam queryParam = new StoreDepartmentQueryParam();
        queryParam.setStoreId(storeId);
        List<Map> storeDeptlist = storeDepartmentService.storeDeptList(queryParam);
        Company company = new Company();
        company = companyService.getById(comanyId);
        addMap.put("company",company);
        addMap.put("storeUserList",newPage);
        JSONArray deptResult = listToTree(JSONArray.parseArray(JSON.toJSONString(storeDeptlist)),"id","parent_id","children");
        addMap.put("storeDeptlist",deptResult);//JSON.toJSONString(deptResult));
        //addMap.put("storeDeptlist",storeDeptlist);
        return Response.data(addMap);
    }

    /**
     *
     * @Description: 店铺管理-->角色列表
     *
     * @param page
     * @param param
     * @param key
     * @return
     */
    @Override
    public Response getRoleList(IPage<StoreUsersVO> page,@Param("param")StoreUsersQueryParam param, String key){
        Map addMap = new HashMap<>();

        List<SysRoles> roleList = sysRolesService.getAllSaasRoleList(4);

        SysUsersQueryParam sysUsersQueryParam = new SysUsersQueryParam();
        sysUsersQueryParam.setPageNumber(String.valueOf(page.getCurrent()));
        sysUsersQueryParam.setPageSize(String.valueOf(page.getSize()));
        IPage<StoreUsersVO> newPage = storeUsersService.getStoreUserByRoleName(page,param);//sysUsersService.getAllEmployee(page,sysUsersQueryParam);
        addMap.put("roleList",roleList);
        addMap.put("userList",newPage);
        return Response.data(addMap);
    }

    /**

     - listToTree
     - <p>方法说明<p>
     - 将JSONArray数组转为树状结构
     - @param arr 需要转化的数据
     - @param id 数据唯一的标识键值
     - @param pid 父id唯一标识键值
     - @param child 子节点键值
     - @return JSONArray
     */
    @Override
    public JSONArray listToTree(JSONArray arr, String id, String pid, String child){
        JSONArray r = new JSONArray();
        JSONObject hash = new JSONObject();
        //将数组转为Object的形式，key为数组中的id
        for(int i=0;i<arr.size();i++){
            JSONObject json = (JSONObject) arr.get(i);
            hash.put(json.getString(id), json);
        }
        //遍历结果集
        for(int j=0;j<arr.size();j++){
            //单条记录
            JSONObject aVal = (JSONObject) arr.get(j);
            //在hash中取出key为单条记录中pid的值

            JSONObject hashVP = (JSONObject) hash.get(aVal.get(pid).toString());
            //如果记录的pid存在，则说明它有父节点，将她添加到孩子节点的集合中
                //检查是否有child属性
                if(hashVP!=null){
                    //JSONObject hashVP = (JSONObject) hash.get(aVal.get(pid).toString());
                    if(hashVP.get(child)==null){
                        JSONArray ch = new JSONArray();
                        ch.add(aVal);
                        hashVP.put(child, ch);
                    }else{
                        JSONArray ch = (JSONArray) hashVP.get(child);
                        ch.add(aVal);
                        hashVP.put(child, ch);
                    }
                }else{
                    r.add(aVal);
                }
            }

        return r;
    }

    public static void main(String[] args){
        List<Map<String,Object>> data = new ArrayList<>();
        Map<String,Object> map = new HashMap<>();
        map.put("id",1);
        map.put("pid",0);
        map.put("name","甘肃省");
        data.add(map);
        Map<String,Object> map2 = new HashMap<>();
        map2.put("id",2);
        map2.put("pid",1);
        map2.put("name","天水市");
        data.add(map2);
        Map<String,Object> map3 = new HashMap<>();
        map3.put("id",3);
        map3.put("pid",2);
        map3.put("name","秦州区");
        data.add(map3);
        Map<String,Object> map4 = new HashMap<>();
        map4.put("id",4);
        map4.put("pid",0);
        map4.put("name","北京市");
        data.add(map4);
        Map<String,Object> map5 = new HashMap<>();
        map5.put("id",5);
        map5.put("pid",4);
        map5.put("name","昌平区");
        data.add(map5);
        System.out.println(JSON.toJSONString(data));
        JSONArray result = null;//listToTree(JSONArray.parseArray(JSON.toJSONString(data)),"id","pid","children");
        System.out.println(JSON.toJSONString(result));
    }

}
